<template>
  <div id="container" ref="mapRef"></div>
</template>
  
<script setup>
import AMapLoader from "@amap/amap-jsapi-loader";
const mapRef = ref(null)
const selectMap = ref()
const map = ref()
const address = ref()
const marker = ref(null)
const emit = defineEmits(["setAddress", "setLnglat"]);
const props = defineProps({
  longitude: {
    type: Number,
    required: true
  },
  latitude: {
    type: Number,
    required: true
  }
})
watch(() => [props.longitude, props.latitude], ([longitudeNewVal], [latitudenewVal]) => {
  let AMap = selectMap.value
  let lnglat = [props.longitude, props.latitude]
  console.log(marker.value)
  map.value.setZoomAndCenter(15, lnglat);
  AMap.plugin("AMap.Geocoder", function () {
    const geocoder = new AMap.Geocoder({
      city: '010',
    })
    geocoder.getAddress(lnglat, function (status, result) {
      if (status === 'complete' && result.info === 'OK') {
        // result为对应的地理位置详细信息
        address.value = result.regeocode.addressComponent
        console.log(result.regeocode.addressComponent)
        emit("setAddress", result.regeocode.addressComponent)
      }
    })
  })

});
//进行地图初始化
function initMap() {
  window._AMapSecurityConfig = {
    securityJsCode: '7285e9ad147fbe0b3defddae9256abbe',
  }
  AMapLoader.load({
    key: "5c965626eed2b7c321bf329e4e0fc9d2", // 申请好的Web端开发者Key，首次调用 load 时必填
  }).then((AMap) => {
    selectMap.value = AMap
    var satellite = new AMap.TileLayer.Satellite();
    var roadNet = new AMap.TileLayer.RoadNet();
    map.value = new AMap.Map(mapRef.value, {
      //设置地图容器id
      viewMode: "3D", //是否为3D地图模式
      zoom: 10, //初始化地图级别
      layers: [
        satellite,
        roadNet
      ]
      // resizeEnable: true,

    });

    // 单击
    map.value.on("click", (e) => {
      console.log(e.lnglat);
      emit("setLnglat", e.lnglat)
      if (marker.value !== null) {
        map.value.remove(marker.value);
      }
      marker.value = new AMap.Marker({
        position: new AMap.LngLat(e.lnglat.lng, e.lnglat.lat),
        title: '井'
      });
      map.value.add(marker.value)
    });
  })
    .catch((e) => {
      console.log(e);
    });

}

initMap();
</script>
  
<style scoped>
#container {
  padding: 0px;
  margin: 0px;
  width: 100%;
  height: 40vh;
}
</style>